<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\logic;

use app\common\logic\Vip as CommonVip;

/**
 * VIP管理逻辑层（后台专用）
 */
class Vip extends AdminBase
{
    /**
     * @var CommonVip
     */
    public static $commonVipLogic;
    
    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
        
        empty(static::$commonVipLogic) && static::$commonVipLogic = new CommonVip();
    }
    /**
     * 获取VIP订单搜索条件
     * @param array $data 搜索参数
     * @return array
     */
    public function getWhere($data = [])
    {
        return static::$commonVipLogic->getWhere($data);
    }
    
    /**
     * 获取VIP套餐搜索条件
     */
    public function getPackageWhere($data = [])
    {
        $where = [];
        
        // 套餐名称搜索
        if (!empty($data['search_data'])) {
            $where['level_name|price'] = ['like', '%' . $data['search_data'] . '%'];
        }
        
        // 状态搜索
        if (isset($data['status']) && $data['status'] !== '') {
            $where['status'] = $data['status'];
        }
        
        return $where;
    }
    
    /**
     * VIP订单列表
     */
    public function getVipList($where = [], $field = true, $order = '', $paginate = false)
    {
        // 设置别名和关联查询
        $this->modelVipOrder->alias_name = 'vo';
        $this->modelVipOrder->join = [
            ['user u', 'u.id = vo.user_id', 'LEFT']
        ];
        
        // 如果field为true，设置默认字段
        if ($field === true) {
            $field = 'vo.*, u.nickname, u.mobile';
        }
        
        $list = $this->modelVipOrder->getList($where, $field, $order, $paginate);
        
        // 清理属性，避免影响后续查询
        $this->modelVipOrder->join = [];
        $this->modelVipOrder->alias_name = '';
        
        return $list;
    }
    
    /**
     * 获取VIP统计数据
     */
    public function getVipStats($data = [])
    {
        $stats = [];
        
        // 今日新增VIP订单
        $today_start = date('Y-m-d 00:00:00');
        $today_end = date('Y-m-d 23:59:59');
        $stats['today_orders'] = $this->modelVipOrder->stat([
            'create_time' => ['between', [$today_start, $today_end]]
        ]);
        
        // 今日VIP收入
        $stats['today_income'] = $this->modelVipOrder->stat([
            'create_time' => ['between', [$today_start, $today_end]],
            'order_status' => 1  // 已支付状态
        ], 'sum', 'amount') ?: 0;
        
        // 总VIP订单数
        $stats['total_orders'] = $this->modelVipOrder->stat([]);
        
        // 总VIP收入
        $stats['total_income'] = $this->modelVipOrder->stat([
            'order_status' => 1  // 已支付状态
        ], 'sum', 'amount') ?: 0;
        
        // 有效VIP用户数（已支付订单的用户数）
        $stats['active_vip_users'] = $this->modelVipOrder->stat([
            'order_status' => 1  // 已支付状态
        ], 'count', 'DISTINCT user_id') ?: 0;
        
        // 待支付订单数
        $stats['pending_orders'] = $this->modelVipOrder->stat([
            'order_status' => 0  // 待支付状态
        ]);
        
        // 获取套餐销售统计
        $stats['package_stats'] = $this->getPackageStats();
        
        return $stats;
    }
    
    /**
     * 获取套餐销售统计
     */
    private function getPackageStats()
    {
        // 使用原生SQL查询来实现GROUP BY，基于VIP订单表和套餐表
        // 修复GROUP BY语法错误，添加vp.name字段以符合ONLY_FULL_GROUP_BY模式
        $sql = "SELECT vp.name, COUNT(vo.id) as count, SUM(vo.amount) as amount 
                FROM " . SYS_DB_PREFIX . "vip_order vo 
                LEFT JOIN " . SYS_DB_PREFIX . "vip_package vp ON vp.type = vo.package_type 
                WHERE vo.order_status = 1 
                GROUP BY vo.package_type, vp.name 
                ORDER BY count DESC";
        
        $list = \think\facade\Db::query($sql);
        
        // 计算总金额用于计算占比
        $totalAmount = array_sum(array_column($list, 'amount'));
        
        // 处理数据格式
        $packageStats = [];
        foreach ($list as $item) {
            $percent = $totalAmount > 0 ? round(($item['amount'] / $totalAmount) * 100, 2) : 0;
            $packageStats[] = [
                'name' => $item['name'] ?: '未知套餐',
                'count' => $item['count'],
                'amount' => number_format($item['amount'], 2),
                'percent' => $percent
            ];
        }
        
        return $packageStats;
    }
    
    /**
     * 获取套餐列表
     */
    public function getPackageList($where = [], $field = true, $order = 'sort asc, id asc', $paginate = false)
    {
        return $this->modelVipPackage->getList($where, $field, $order, $paginate);
    }
    
    /**
     * 套餐管理
     */
    public function packageManage($data = [])
    {
        $url = url('packages');
        
        $validate_result = $this->validateVipPackage->scene('edit')->check($data);
        
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateVipPackage->getError()];
        }
        
        $result = static::$commonVipLogic->packageManage($data);
        
        if (is_array($result) && $result[0] == RESULT_ERROR) {
            return $result;
        }
        
        action_log('VIP套餐', 'VIP套餐管理，id：' . $data['id']);
        
        return [RESULT_SUCCESS, '套餐管理成功', $url];
    }
    
    /**
     * 套餐添加
     */
    public function packageAdd($data = [])
    {
        $url = url('packageList');
        
        $validate_result = $this->validateVipPackage->scene('add')->check($data);
        
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateVipPackage->getError()];
        }
        
        $result = static::$commonVipLogic->packageAdd($data);
        
        if (is_array($result) && $result[0] == RESULT_ERROR) {
            return $result;
        }
        
        action_log('VIP套餐', 'VIP套餐添加');
        
        return [RESULT_SUCCESS, '套餐添加成功', $url];
    }
    
    /**
     * 套餐编辑
     */
    public function packageEdit($data = [])
    {
        $url = url('packageList');
        
        $validate_result = $this->validateVipPackage->scene('edit')->check($data);
        
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateVipPackage->getError()];
        }
        
        $result = static::$commonVipLogic->packageEdit($data);
        
        if (is_array($result) && $result[0] == RESULT_ERROR) {
            return $result;
        }
        
        action_log('VIP套餐', 'VIP套餐编辑，id：' . $data['id']);
        
        return [RESULT_SUCCESS, '套餐编辑成功', $url];
    }
    
    /**
     * 获取套餐信息
     */
    public function getPackageInfo($where = [], $field = true)
    {
        $result = static::$commonVipLogic->getPackageInfo($where, $field);
        
        if (is_array($result) && $result[0] == RESULT_ERROR) {
            return [];
        }
        
        return $result[2] ?? [];
    }

    /**
     * 套餐删除
     */
    public function packageDel($data = [])
    {
        $result = static::$commonVipLogic->packageDel($data);
        
        if (is_array($result) && $result[0] == RESULT_ERROR) {
            return $result;
        }
        
        action_log('VIP套餐', 'VIP套餐删除，id：' . $data['id']);
        
        return [RESULT_SUCCESS, '套餐删除成功'];
    }
    
    /**
     * 获取VIP订单详情
     */
    public function getVipInfo($where = [], $field = true)
    {
        // 设置主表别名
        $this->modelVipOrder->alias_name = 'vo';
        
        // 设置关联查询
        $this->modelVipOrder->join = [
            ['user u', 'u.id = vo.user_id', 'LEFT']
        ];
        
        // 设置查询字段
        if ($field === true) {
            $field = 'vo.*, u.nickname, u.mobile, u.head_img_id';
        }
        
        $info = $this->modelVipOrder->getInfo($where, $field);
        
        // 清理属性，避免影响后续查询
        $this->modelVipOrder->join = [];
        $this->modelVipOrder->alias_name = '';
        
        return $info;
    }
    
    /**
     * VIP订单状态管理
     */
    public function vipStatus($data = [])
    {
        $result = static::$commonVipLogic->vipStatus($data);
        
        if (is_array($result) && $result[0] == RESULT_ERROR) {
            return $result;
        }
        
        action_log('VIP状态', 'VIP订单状态管理，id：' . $data['id']);
        
        return [RESULT_SUCCESS, 'VIP状态更新成功'];
    }
    
    /**
     * 导出VIP订单列表
     */
    public function exportVipList($where = [])
    {
        return static::$commonVipLogic->exportVipList($where);
    }
    
    /**
     * 激活VIP订单
     */
    public function vipActivate($data = [])
    {
        $id = $data['id'] ?? 0;
        if (!$id) {
            return [RESULT_ERROR, '订单ID不能为空'];
        }
        
        // 获取订单信息
        $orderInfo = $this->modelVipOrder->getInfo(['id' => $id]);
        if (!$orderInfo) {
            return [RESULT_ERROR, '订单不存在'];
        }
        
        if ($orderInfo['status'] != 0) {
            return [RESULT_ERROR, '只能激活待支付状态的订单'];
        }
        
        // 更新订单状态为已支付
        $updateData = [
            'status' => 1,
            'pay_time' => time(),
            'update_time' => time()
        ];
        
        $result = $this->modelVipOrder->updateInfo(['id' => $id], $updateData);
        
        if ($result) {
            // 激活用户VIP权限
            static::$commonVipLogic->activateVipByOrder($orderInfo);
            
            action_log('VIP订单', 'VIP订单激活，id：' . $id);
            return [RESULT_SUCCESS, 'VIP订单激活成功'];
        } else {
            return [RESULT_ERROR, 'VIP订单激活失败'];
        }
    }
    
    /**
     * 取消VIP订单
     */
    public function vipCancel($data = [])
    {
        $id = $data['id'] ?? 0;
        if (!$id) {
            return [RESULT_ERROR, '订单ID不能为空'];
        }
        
        // 获取订单信息
        $orderInfo = $this->modelVipOrder->getInfo(['id' => $id]);
        if (!$orderInfo) {
            return [RESULT_ERROR, '订单不存在'];
        }
        
        if ($orderInfo['status'] != 0) {
            return [RESULT_ERROR, '只能取消待支付状态的订单'];
        }
        
        // 更新订单状态为已取消
        $updateData = [
            'status' => 2,
            'update_time' => time()
        ];
        
        $result = $this->modelVipOrder->updateInfo(['id' => $id], $updateData);
        
        if ($result) {
            action_log('VIP订单', 'VIP订单取消，id：' . $id);
            return [RESULT_SUCCESS, 'VIP订单取消成功'];
        } else {
            return [RESULT_ERROR, 'VIP订单取消失败'];
        }
    }
    
    /**
     * 退款VIP订单
     */
    public function vipRefund($data = [])
    {
        $id = $data['id'] ?? 0;
        if (!$id) {
            return [RESULT_ERROR, '订单ID不能为空'];
        }
        
        // 获取订单信息
        $orderInfo = $this->modelVipOrder->getInfo(['id' => $id]);
        if (!$orderInfo) {
            return [RESULT_ERROR, '订单不存在'];
        }
        
        if ($orderInfo['status'] != 1) {
            return [RESULT_ERROR, '只能退款已支付状态的订单'];
        }
        
        // 更新订单状态为已退款
        $updateData = [
            'status' => 3,
            'update_time' => time()
        ];
        
        $result = $this->modelVipOrder->updateInfo(['id' => $id], $updateData);
        
        if ($result) {
            // 取消用户VIP权限
            static::$commonVipLogic->cancelVipByOrder($orderInfo);
            
            action_log('VIP订单', 'VIP订单退款，id：' . $id);
            return [RESULT_SUCCESS, 'VIP订单退款成功，用户VIP权限已取消'];
        } else {
            return [RESULT_ERROR, 'VIP订单退款失败'];
        }
    }
}